var VocaSettings={
	MAXIMUM_WORDS_TO_COLLECT_A_TIME:15
}

var VocaMessage={
	system_error:'发生系统错误，操作失败。<br />请帮助我们完善系统，将问题提交到<a href="/group/topics.php?group_id=2" target="_blank">问题汇报区</a>，使问题尽快得到解决。'
}

var VocaHTML={
	word_input:'<input type="text" class="word_input text_input_simple" />',
	ajax_loader_gif:'/assets/images/ajax-loader.gif',
	ajax_loader_small_gif:'/assets/images/ajax-loader-small.gif',
	waiting:'<span><img src="/assets/images/ajax-loader.gif"/ align="absmiddle">&nbsp;处理中，请稍后。</span>',
	loading: function(text,type){
		var img = '<img src="'+VocaHTML.ajax_loader_gif+'" width="31" height="31" align="absmiddle"/>';
		if(type=='small'){
			img = '<img src="'+VocaHTML.ajax_loader_small_gif+'" width="16" height="11" align="absmiddle"/>';
		}
		if(text){
			return img+'&nbsp;'+text+'...';
		}else{
			return img;
		}
	}
}

var VocaHandlerURL={
	user_word:'/handlers/user_word_handler.php',
	word_definition:'/handlers/word_definition_handler.php',
	sentence:'/handlers/sentence_handler.php',
	note:'/handlers/note_handler.php',
	post:'/handlers/post_handler.php',
	course:'/handlers/course_handler.php',
	learning:'/handlers/learning_handler.php'
}

var KeyCode={
	BACKSPACE:8,
	TAB:9,
	ENTER:13,
	DELETE:46
}

String.prototype.getBytes = function(){
	var cArr = this.match(/[^\x00-\xff]/ig);
	return this.length + (cArr == null ? 0 : cArr.length);
}

String.prototype.containsChinese = function(){
	if($.trim(this)=='')return false;
	if(/.*[\u4e00-\u9fa5]+.*$/.test(this)){
		return true;
	}
	return false;
}

function trim_comma(s){
	return $.trim(s).substring(0,s.length-1);
}

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

$.fn.message = function(success,content){
	this.addClass('message_box');
	if(success){
		this.removeClass('failure_message_box');
		this.addClass('success_message_box')
	}else{
		this.removeClass('success_message_box');
		this.addClass('failure_message_box');
	}
	this.html(content);
	return this;
}

$.fn.live=function(trigger_event,callback){
	return $(document).on(trigger_event,this.selector,callback);
}

$.fn.blink=function(){
	var bg_color = $(this).css('background-color');;
	$(this).stop().animate({backgroundColor:'yellow'},1000,function(){
		$(this).stop().animate({backgroundColor:bg_color},1000,function(){
			$(this).css({backgroundColor:''});
		});
	});
}

$.fn.remove_trigger = function(yes_fn,no_fn){
	var selector= $(this).selector;
	$(document).on('click',selector,function(evt){
		$this = $(this);
		$this.fadeOut('fast',function(){
			$this.after('<a href="#" class="cancel_remove">取消</a>');
			$this.after('<span class="separator_yes_and_cancel">&nbsp;/&nbsp;</span>');
			$this.after('<a href="#" class="continue_remove">确认删除</a>');
		});
		return false;
	});
	$(this).parent().off('click','.continue_remove').on('click','.continue_remove',function(){
		yes_fn($this);
		return false;
	});
	$(this).parent().off('click','.cancel_remove').on('click','.cancel_remove',function(){
		$(this).siblings('.continue_remove,.separator_yes_and_cancel').remove();
		$(this).css('display','none');
		if($.isFunction(no_fn)){
			no_fn();
		}
		$(this).siblings('.remove_confirm').fadeIn();
		$(this).siblings(selector).fadeIn();
		$(this).remove();
		return false;
	});
}

$.fn.remove_trigger.restore=function($trigger){
	$trigger.siblings('.continue_remove,.separator_yes_and_cancel,.cancel_remove').remove();
	$trigger.css('display','');
}

$.fn.ajax_animation=function($trigger,gif_type,callback){
	var animation=VocaHTML.waiting;
	if(gif_type=='small'){
		animation=VocaHTML.loading(null,'small');
	}
	$(document).ajaxStart(function(){
		$trigger.css('display','none').after(animation);
	});
	$(document).ajaxStop(function(){
		$trigger.next().remove();
		$trigger.fadeIn();
		$(document).off('ajaxStart');
		$(document).off('ajaxStop');
	});
}

$.html={
	form:function(url,data){
		var form='<form action="'+url+'" method="post">';
		$.each(data, function(key, val) {
			form+='<input type="hidden" name="'+key+'" value="'+val+'"/>';
		});
		form+='</form>';
		return form;
	}
}

$.fn.sync_post=function(url,data){
	var $form = $($.html.form(url,data));
	$form.appendTo('body');
	$form.get(0).submit();
}

$.fn.dialog={
	post:function($trigger,url,data,success,fail){
		$dialog=$trigger.parents('.dialog');
		$response = $dialog.find('.response');
		$cancel=$trigger.siblings('.btn_close_dialog');
		$cancel.fadeOut('fast');

		function restore_buttons(){
			$trigger.fadeIn('fast');
			$cancel.fadeIn('fast');
		}
		$.fn.ajax_animation($trigger);
		$.post( url, data, function(json){
			restore_buttons();
			$response.html('').css('display','none');
			if(json.success){
				if($.isFunction(success)){
					success();
				}
				$dialog.find('.response').fadeOut().html('');
				$dialog.bPopup().close();
			}else{
				$dialog.find('.response').message(false,VocaMessage.system_error).fadeIn();
				if($.isFunction(fail)){
					fail();
				}
			}
		},
		'json'
		).fail(function(){
			restore_buttons();
			$dialog.find('.response').message(false,VocaMessage.system_error).fadeIn();
			if($.isFunction(fail)){
				fail();
			}
		});
	},
	popup:function($dialog){
		$dialog.bPopup({
			modalClose: false,
            opacity: 0.6,
            positionStyle: 'fixed'
		});
	}
}

$([VocaHTML.ajax_loader_gif, VocaHTML.ajax_loader_small_gif]).preload();

function error_dialog(){
	var $message_dialog=$('#message_dialog');
	$message_dialog.find('.dialog_content div').message(false,VocaMessage.system_error);
	$.fn.dialog.popup($message_dialog);
}

function init_dropdown(){
	$('.dropdown li').hover(
	    function () {
	        $('ul', this).stop().slideDown(100);
	    },
	    function () {
	        $('ul', this).stop().slideUp(100);
	    }
	);
}

function save_to_cookie($trigger, key,callback){
	$trigger.click(function(){
		var value=$(this).attr('value');
		if(value!=undefined){
			$.cookie(key, value);
		}else{
			$.removeCookie(key);
		}
		if($.isFunction(callback)){
			callback();
		}
		return false;
	});
}

$(document).ready(function(){
	init_dropdown();
	if($.fn.elastic){
		$('textarea').elastic();

	}
	/*
	* 批量收藏单词
	*/
	$('#btn_collect_words').click(function(){
		var words='';
		$.each($('.word_input'),function(idx,obj){
			var word = $.trim($(obj).val());
			if(word!=''){
				words+=word+',';
			}
		})
		if(words==''){
			$('.response').message(false,'请输入你要收藏的单词');
			return;
		}
		words=trim_comma(words);
		$.post(
			VocaHandlerURL.user_word,
			{action:'collect_words',words:words},
			function(json){
				if(json.success>0){
					var collected_words_html='';
					$.each(json.collected_words,function(idx,obj){
						collected_words_html+='<a href="/word.php?word='+encodeURI(obj)+'" class="word_item">'+obj+'</a>';
					});
					$.each(json.forgot_words,function(idx,obj){
						collected_words_html+='<a href="/word.php?word='+encodeURI(obj)+'" class="word_item forgot_word">'+obj+'</a>';
					});
					var message=json.success+'个单词已收藏到你的个人词库<br/>';
					if(json.forgot_words.length>0){
						message+='其中橙色单词你在以前添加过，'+
						'这表示你可能已经忘记了这些单词,我们将会重新设置你对这些单词的熟悉程度。<br/>';
					}
					message+='<div">'+collected_words_html+'</div>'
					$('.response').message(true,message);
				}else{
					$('.response').message(false,'没有单词收藏到你的个人词库');
				}
				$('.response').fadeIn();
				$('.word_input').val('');
				var $words_no_exist=$("#words_no_exist");
				$words_no_exist.empty();
				if(json.failed>0){
					$.each(json.failed_words,function(idx,obj){
						$words_no_exist.append('<LI>'+obj.replace(/["]/g,'')+'</LI>');
					});	
					$('#sidebar').fadeIn();
					$('#redirect_to_add_words > input[name="words"]').val(JSON.stringify(json.failed_words));
				}else{
					$('#sidebar').fadeOut();
				}
			},
			'json'
		).fail(function(){
				$('.response').message(false,VocaMessage.system_error).fadeIn();
		});
	});

	/*
	* 收藏单词
	*/
	$('.word .collect_word').click(function(){
		$this=$(this);
		$.fn.ajax_animation($(this),'small');
		$.post(
			VocaHandlerURL.user_word,
			{action:'collect_word',word_id:$(this).attr("data")},
			function(json){
				$this.next().remove();
				if(json.success){
					$this.replaceWith('<span class="grey_small" user_word_id="'+json.user_word_id+'">已收藏</span>')
					.css('display','');
					$('.ui-progress').css('width','20%');
				}else{
					$this.fadeIn();
					error_dialog();
				}
			},
			'json'
		).fail(function(){
			$this.fadeIn();
			error_dialog();
		})
	});

	/*
	* 跳转到添加单词页面
	*/
	$('#to_add_words').click(function(){
		$('#redirect_to_add_words').get(0).submit();
	});
	
	/*
	* 添加单词
	*/
	
	$('.word_input, .definition_input').keydown(function(){
		$(this).removeClass('text_input_simple_invalid');
	});

	$('#btn_add_words').click(function(){
		var json_data={};
		var $word_input=$('.word_input');
		var is_valid=true;
		var word_links='';
		$.each($word_input,function(idx,obj){
			var no = $(obj).attr('id').split('_')[1];
			var $definition_input = $('#definition_'+no);
			var word = $.trim($(obj).val()).toLowerCase();
			var definition = $.trim($definition_input.val());
			if(word==''&&definition!=''){
				$definition_input.addClass('text_input_simple_invalid');
				is_valid=false;
			}
			if(word!=''&&definition==''){
				$definition_input.addClass('text_input_simple_invalid');
				is_valid=false;
			}
			if(word!=''&&definition!=''){
				if(!json_data[word]){
					word_links+='<a href="/word.php?word='+encodeURI(word)+'" class="word_item">'+word+'</a>';
				}
				json_data[word]=definition;
			}
		});
		if(!is_valid){
			$('.notice').fadeIn();
		}else{
			$('input').attr('disabled',true);
			$('.notice').fadeOut();
			$.post(
				VocaHandlerURL.word_definition,
				{words:JSON.stringify(json_data)},
				function(json){
					if(json.success){
						$('input').removeAttr('disabled');
						$('.word_and_definition').css('display','none');
						$('.response').message(true,'下列单词已添加</br>'+
							word_links+
							'<div><a href="collect_words.php">继续收藏单词</a>&nbsp;&nbsp;'+
							'<a href="my_vocabulary.php">我的词库</a></div>'
						);
					}else{
						$('.response').message(false,VocaMessage.system_error);
					}
				},
				'json'
			).fail(function(){
				$('input').removeAttr('disabled');
				$('.response').message(false,VocaMessage.system_error);
			});
		}
	});

	/*
	*退出系统
	*/
	$('#logout').click(function(){
		$(this).parent().get(0).submit();
	});

	/*
	* 个人词库排序过滤
	*/
	save_to_cookie($('.order_by a'),'my_vocabulary_order',function(){window.location.href='/vocabulary'});
	save_to_cookie($('.filter a'),'my_vocabulary_filter',function(){window.location.href='/vocabulary'})

	/*
	* 显示和隐藏个人词库每个词条的可执行操作
	*/
	$('.word_list_item').hover(
		function(){
			$(this).find('.operation').removeClass('hidden');
		},
		function(){
			$(this).find('.operation').addClass('hidden');
		}
	)

	/*
	* 个人词库中词条的删除操作
	*/
	$('.my_vocabulary .word_list_item').mouseleave(function(){
		$.fn.remove_trigger.restore($('.remove_user_word'));
	});

	$('.remove_user_word').remove_trigger(function($trigger){
		$word_item=$trigger.parents('.word_list_item');
		$.fn.sync_post(
			VocaHandlerURL.user_word,
			{
				action:'remove',
				word_id: $word_item.find('.data_word_id').val(),
				word: $word_item.find('.data_word').val()
			}
		);
	});

	/*
	* 设置对单词的熟悉程度
	*/
	function set_familiarity($trigger,familiarity, word_id){
		$.post(
			VocaHandlerURL.user_word,
			{
				action:'set_familiarity',
				familiarity:familiarity,
				word_id: word_id
			},
			function(json){
				if(json.success){
					$progress = familiarity*20;
					$ui_progress=$trigger.parents('.word_list_item').find('.ui-progress');
					if($progress==100){
						$ui_progress.css('width','100%').parent().attr('class','ui-progress-bar success ui-container');
						$trigger.attr('class','btn_i_forgot').text('我忘了');
					}else{
						$ui_progress.css('width','20%').parent().attr('class','ui-progress-bar blue ui-container');
						$trigger.attr('class','btn_so_easy').text('太简单');
					}
				}
			},
			'json'
		).fail(function(){
			error_dialog();
		});
	}

	$(document).on('click','.btn_so_easy, .btn_i_forgot', function(){
		$this=$(this);
		$.fn.ajax_animation($this,'small');
		$word_item = $this.parents('.word_list_item');
		if($this.attr('class') == 'btn_so_easy'){
			set_familiarity($this,5,$word_item.find('.data_word_id').val());
		}else{
			set_familiarity($this,1,$word_item.find('.data_word_id').val());
			
		}
	});

	$('.my_vocabulary .response').fadeOut(3000);
	
	/*
	* 初始化TabPanel
	*/
	if($.fn.easytabs){
		$('.tabs').easytabs({cache:false});
	}
	$('.tabs .sentences').bind('easytabs:ajax:beforeSend', function(e, clicked, panel){
		panel.html(VocaHTML.loading('例句加载中'));
    });
    $('.tabs .notes').bind('easytabs:ajax:beforeSend', function(e, clicked, panel){
		panel.html(VocaHTML.loading('笔记加载中'));
    });

    function reload_active_tab(selector){
    	var $tabs = $(selector);
    	var $tab = $tabs.find('.panel_container div.active');
    	$tab.html(VocaHTML.loading('例句加载中'));
    	var tab_id = $tab.attr('id');
    	var url=$tabs.find('a.active[data-target="#'+tab_id+'"]').attr('href');
    	$tab.load(url);
    }

	/*
	* 不允许单词包含单双引号，自动过滤
	*/
	$('.word_input').keyup(function(){
		var value = $(this).val();
		if(value.indexOf("'")>-1 || value.indexOf('"')>-1){
			$(this).val(value.replace(/['"]/g,''));
		}
	});

	/*
	* 在连续的输入框中快捷的移动焦点
	*/
	$(':input[type="text"]').keydown(function(e) {
	    if ((e.which == KeyCode.BACKSPACE || e.which == KeyCode.DELETE) && $(this).val() =='') {
	        $(this).prev('input[type="text"]').focus();
	    }else if(e.which == KeyCode.ENTER){
	    	$(this).next('input[type="text"]').focus();
	    }
	});


	/*
	* 修改单词定义对话框
	*/
	$('.btn_edit_definition').click(function(){
		$.fn.dialog.popup($('#edit_definition_dialog'));
		return false;
	});

	$('#definition_input').keydown(function(e){
		if(e.which == KeyCode.ENTER){
			$('#btn_edit_definition').trigger('click');
		}
	});
	/*
	* 修改单词定义
	*/
	$('#btn_edit_definition').click(function(){
		var $definition_input = $('#definition_input');
		var $response = $(this).parents('.dialog').find('.response');
		var old_definition = $('#old_definition').val();
		var definition = $definition_input.val();
		if(definition===old_definition){
			$(this).parents('.dialog').bPopup().close();
		}else{
			definition=$.trim(definition);
			if(definition==''){
				$definition_input.addClass('text_input_simple_invalid');
				$response.message(false,'请填写单词定义').fadeIn();
			}else{
				$.fn.dialog.post($(this),
					VocaHandlerURL.word_definition,
					{
						action:'edit',
						word_id:$('#data_word_id').val(),
						definition:$definition_input.val()
					},
					function(){
						$('.definition div').text(definition).blink();
						$('#old_definition').val(definition);
						$response.fadeOut().html('');
					}
				);
			}
		}
	});

	/*
	* 添加例句对话框
	*/
	$('.btn_open_sentence_dialog').click(function(){
		$('#sentence_dialog').find('.dialog_header').text('添加例句');
		$('#sentence_id').val('');
		$.fn.dialog.popup($('#sentence_dialog'));
		return false;
	});

	$('#sentence_input, #translation_input').keydown(function(e){
		if(e.which == KeyCode.ENTER){
			$('#btn_save_sentence').trigger('click');
		}
	});

	function sentence_validation($sentence_input,$translation_input){
		var invalid_message='';
		if($.trim($sentence_input.val())==''){
			is_valid=false;
			$sentence_input.addClass('text_input_simple_invalid');
			invalid_message='例句不能为空&nbsp;&nbsp;';
		}else if($sentence_input.val().containsChinese()){
			is_valid=false;
			invalid_message+='请不要在例句中使用中文&nbsp;&nbsp;';
			$sentence_input.addClass('text_input_simple_invalid');
		}else{
			$sentence_input.removeClass('text_input_simple_invalid');
		}

		if($.trim($translation_input.val())==''){
			is_valid=false;
			$translation_input.addClass('text_input_simple_invalid');
			invalid_message+='翻译不能为空&nbsp;&nbsp;';
		}else if(!$translation_input.val().containsChinese()){
			is_valid=false;
			$translation_input.addClass('text_input_simple_invalid');
			invalid_message+='翻译请使用中文';
		}else{
			$translation_input.removeClass('text_input_simple_invalid');
		}
		return invalid_message;
	}
	
	/*
	* 保存例句
	*/
	$('#btn_save_sentence').click(function(){
		var $sentence_input = $('#sentence_input');
		var $translation_input = $('#translation_input');
		var invalid_message=sentence_validation($sentence_input,$translation_input);
		if(invalid_message==''){
			$.fn.dialog.post($(this),
				VocaHandlerURL.sentence,
				{
					action:'save',
					word_id:$('#data_word_id').val(),
					sentence:$sentence_input.val(),
					translation:$translation_input.val(),
					sentence_id:$('#sentence_id').val()
				},
				function(){
					$('#sentence_input,#translation_input').removeClass('text_input_simple_invalid').val('');
					$('#sentence_id').val('');
					reload_active_tab('.sentences');
				}
			);
		}else{
			$(this).parents('.dialog').find('.response').message(false,invalid_message).fadeIn();
		}
	});

	$('.a_sentence').live('mouseenter',function(){
		$(this).find(".actions").css('visibility','visible');
	});
	$('.a_sentence').live('mouseleave',function(){
		$(this).find(".actions").css('visibility','hidden');
	});
	/*
	* 收藏例句
	*/
	$('.a_sentence a.like').live('click',function(){
		var $this=$(this);
		$.fn.ajax_animation($this,'small');
		$.post(
			VocaHandlerURL.sentence,
			{action:'like',sentence_id: $this.parents('.a_sentence').attr('sentence-id')},
			function(json){
				if(json.success){
					reload_active_tab('.sentences');
				}else{
					error_dialog();
				}
			}
		).fail(function(){
			error_dialog();
		});
	});
	/*
	* 将例句添加到黑名单
	*/
	$('.a_sentence a.dislike').live('click',function(){
		var $this=$(this);
		$.fn.ajax_animation($this,'small');
		$.post(
			VocaHandlerURL.sentence,
			{action:'dislike',sentence_id: $this.parents('.a_sentence').attr('sentence-id')},
			function(json){
				if(json.success){
					reload_active_tab('.sentences');
				}else{
					error_dialog();
				}
			}
		).fail(function(){
			error_dialog();
		});
	});
	/*
	* 修改例句
	*/
	$('.a_sentence a.edit').live('click',function(){
		var $this=$(this);
		var $parent=$this.parents('.a_sentence');
		var sentence_id = $parent.attr('sentence-id');
		var $dialog = $('#sentence_dialog');
		$dialog.find('.dialog_header').text('编辑例句');
		var sentence = $parent.find('.original').text();
		var translation = $parent.find('.translation').text();
		$('#sentence_input').val(sentence);
		$('#translation_input').val(translation);
		$('#sentence_id').val(sentence_id);
		$.fn.dialog.popup($dialog);
		return false;
	});

	/*
	* 删除例句
	*/
	$('.a_sentence a.remove').remove_trigger(function($trigger){
		var sentence_id = $trigger.parents('.a_sentence').attr('sentence-id');
		$.post(
			VocaHandlerURL.sentence,
			{action:'remove',sentence_id: sentence_id},
			function(json){
				if(json.success){
					reload_active_tab('.sentences');
				}else{
					error_dialog();
				}
			}
		).fail(function(){
			error_dialog();
		});
		return false;
	});

	/*
	* 添加笔记对话框
	*/
	$('.btn_open_note_dialog').click(function(){
		$('#note_dialog').find('.dialog_header').text('添加笔记');
		$('#note_id').val('');
		$.fn.dialog.popup($('#note_dialog'));
		return false;
	});
	
	/*
	* 保存笔记
	*/
	$('#btn_save_note').click(function(){
		var $note_input = $('#note_input');
		var invalid_message=''
		if($note_input.val().getBytes()<=6){
			invalid_message='笔记内容不能少于6个字符'
		}
		
		if(invalid_message==''){
			$.fn.dialog.post($(this),
				VocaHandlerURL.note,
				{
					action:'save',
					word_id:$('#data_word_id').val(),
					note:$.trim($note_input.val()),
					note_id:$('#note_id').val()
				},
				function(){
					$('#note_id').val('');
					$('#note_input').val('');
					reload_active_tab('.notes');
				}
			);
		}else{
			$(this).parents('.dialog').find('.response').message(false,invalid_message).fadeIn();
		}
	});

	$('.a_note').live('mouseenter',function(){
		$(this).find(".actions").css('visibility','visible');
	});
	$('.a_note').live('mouseleave',function(){
		$(this).find(".actions").css('visibility','hidden');
	});
	/*
	* 收藏笔记
	*/
	$('.a_note a.like').live('click',function(){
		var $this=$(this);
		$.fn.ajax_animation($this,'small');
		$.post(
			VocaHandlerURL.note,
			{action:'like',note_id: $this.parents('.a_note').attr('note-id')},
			function(json){
				if(json.success){
					reload_active_tab('.notes');
				}else{
					error_dialog();
				}
			}
		).fail(function(){
			error_dialog();
		});
	});
	/*
	* 将笔记添加到黑名单
	*/
	$('.a_note a.dislike').live('click',function(){
		var $this=$(this);
		$.fn.ajax_animation($this,'small');
		$.post(
			VocaHandlerURL.note,
			{action:'dislike',note_id: $this.parents('.a_note').attr('note-id')},
			function(json){
				if(json.success){
					reload_active_tab('.notes');
				}else{
					error_dialog();
				}
			}
		).fail(function(){
			error_dialog();
		});
	});
	/*
	* 修改笔记
	*/
	$('.a_note a.edit').live('click',function(){
		var $this=$(this);
		var $parent=$this.parents('.a_note');
		var note_id = $parent.attr('note-id');
		var $dialog = $('#note_dialog');
		$dialog.find('.dialog_header').text('编辑笔记');
		var note = $parent.find('.note_content').text();
		$('#note_input').val(note);
		$('#note_id').val(note_id);
		$.fn.dialog.popup($dialog);
		return false;
	});

	/*
	* 删除笔记
	*/
	$('.a_note a.remove').remove_trigger(function($trigger){
		var note_id = $trigger.parents('.a_note').attr('note-id');
		$.post(
			VocaHandlerURL.note,
			{action:'remove',note_id: note_id},
			function(json){
				if(json.success){
					reload_active_tab('.notes');
				}else{
					error_dialog();
				}
			}
		).fail(function(){
			error_dialog();
		});
		return false;
	});

	/*
	* 修改头像对话框
	*/
	$('#change_avatar').click(function(){
		$("#avatar_upload_form").get(0).reset();
		$("#bar").width('0%');
		$("#avatar_upload_dialog .message").html("");
		$.fn.dialog.popup($('#upload_avatar_dialog'));
	});

	var options = { 
		beforeSend: function() {
			$("#progress").show();
			$("#bar").width('0%');
			$("#avatar_upload_dialog .message").html("");
		},
		uploadProgress: function(event, position, total, percentComplete) {
			$("#bar").width(percentComplete+'%');
		},
		success: function() {
			$("#bar").width('100%');
			$("#percent").html('100%');
			$('#upload_avatar_dialog').bPopup().close();
			var user_id = $('#dashboard').attr('user-id');
			$('.avatar').find('img').attr('src','/uploads/avatars/avatar_'+user_id+'.png?rand='+Math.random());
		},
		complete: function(response) {
			$("#avatar_upload_dialog .message").html("<font color='green'>"+response.responseText+"</font>");
		},
		error: function(){
			$("#avatar_upload_dialog .message").html("<font color='red'> ERROR: unable to upload files</font>");
		}
	}; 
	if($("#avatar_upload_form").ajaxForm){
		$("#avatar_upload_form").ajaxForm(options);
	}
	/*
	* 关闭对话框
	*/
	$('.btn_close_dialog').click(function(){
		$($(this).parents('.dialog')).bPopup().close();
		return false;
	});

	$('#group_selector_dialog td').click(function(){
		window.location.href=$(this).attr('target-url');
	});
	$('.btn_new_post').click(function(){
		if($(this).attr('href')=="#"){
			$.fn.dialog.popup($('#group_selector_dialog'));
			return false;
		}
		return true;
	});

	/*
	* 发布新贴
	*/
	$('#new_topic_form').submit(function(){
		var title = $.trim($(this).find('#title').val());
		var content = $.trim($(this).find('#content').val());
		var invalid_message='';
		if( title.getBytes()<6){
			invalid_message='标题的长度请不要少于3个汉字或6个英文字符';
		}else if(title.getBytes()>100){
			invalid_message='标题的长度请不要大于50个汉字或100个英文字符';
		}

		if( content.getBytes()<6){
			if(invalid_message!='')invalid_message+='<br />';
			invalid_message+='内容的长度请不要少于3个汉字或6个英文字符';
		}
		if(invalid_message!=''){
			$('.response').message(false,invalid_message);
			return false; 
		}
		return true;
	});

	/*
	* 发布回复
	*/
	$('#reply_form').submit(function(){
		var content = $.trim($(this).find("textarea").val());
		if( content.getBytes()<6){
			$('.response').message(false,"回复的长度请不要少于3个汉字或6个英文字符");
			return false;
		};
		return true;
	});


	/*
	* 删除主题
	*/
	$('.remove_topic').remove_trigger(function($trigger){
		$.fn.sync_post(VocaHandlerURL.post,{'action':'remove_topic','id':$('#data_topic_id').val()});
	});
	/*
	* 编辑回复
	*/
	$('.edit_reply').click(function(){
		var $post=$(this).parents('.post');
		var id = $post.attr('reply-id');
		var content = $.trim($post.find('.content').text());
		$form = $('#reply_form');
		$form.find("input[name='id']").val(id);
		var $textarea = $form.find("textarea");
		$textarea.val(content);
		$textarea.height($textarea[0].scrollHeight);
		$('html, body').animate({
			scrollTop: $("#new_reply").offset().top
		}, 1000);
	});

	/*
	* 删除回复
	*/
	$('.remove_reply').remove_trigger(function($trigger){
		var id=$trigger.parents('.post').attr('reply-id');
		$.fn.sync_post(VocaHandlerURL.post,{'action':'remove_reply','id':id});
	});

});
